package com.zhxh.nzpos.query;

import java.io.IOException;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import pl.polidea.treeview.InMemoryTreeStateManager;
import pl.polidea.treeview.TreeBuilder;
import pl.polidea.treeview.TreeStateManager;
import pl.polidea.treeview.TreeViewList;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;

import com.zhxh.nzpos.R;
import com.zhxh.nzpos.dao.CategoryDao;
import com.zhxh.nzpos.dao.LocalInfoDao;
import com.zhxh.nzpos.dao.SelloutDao;
import com.zhxh.nzpos.goods.GoodsItem;
import com.zhxh.nzpos.model.Category;
import com.zhxh.nzpos.model.LocalInfo;
import com.zhxh.nzpos.model.Statistics;
import com.zhxh.nzpos.serialport.PrintSerialPort;
import com.zhxh.nzpos.utils.ViewUtil;
import com.zhxh.nzpos.view.CustomDatePicker;

/**
 * 统计查询--订购查询
 * 
 * @author wangzt
 * 
 */
public class GoodsQueryActivity extends  PrintSerialPort {

	private ArrayList<GoodsItem> items;
	private ArrayList<Category> categoryItems;
	private ArrayList<Statistics> goodsItems;
	private CategoryDao categoryDao;
	private SelloutDao selloutDao;
	private EditText fromDate;
	private EditText toDate;
	private SimpleDateFormat simpleDateFormat;
	private SimpleDateFormat simpleDateFormat2;
	private String name;
	
	LocalInfoDao dao;
	protected TreeViewList _treeView;
	protected TreeStateManager<Statistics> _stateManager;
	protected TreeBuilder<Statistics> _treeBuilder;

	private Calendar fromCal = Calendar.getInstance();
	private Calendar toCal = Calendar.getInstance();
	
	private SendingThread mSendingThread;
	public static final String PREFS_NAME = "PreferencesFile";

	Map<Statistics, ArrayList<Statistics>> map = new HashMap<Statistics, ArrayList<Statistics>>();
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_query_goods);
		categoryDao = new CategoryDao(this);
		selloutDao = new SelloutDao(this);
		dao = new LocalInfoDao(this);
		_stateManager = new InMemoryTreeStateManager<Statistics>();
		_treeBuilder = new TreeBuilder<Statistics>(_stateManager);

		_treeView = (TreeViewList) findViewById(R.id.mainTreeView);
		_treeView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

		_treeView.setAdapter(new GoodsQueryAdapter(this, _stateManager, 2));
		categoryItems = new ArrayList<Category>();
		initViews();
	}

	private void initViews() {
		items = new ArrayList<GoodsItem>();
		List<LocalInfo> locals = dao.getAll();
		if (locals.size() > 0)
			name = locals.get(0).getName();

		/*
		 * ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
		 * getApplicationContext(), R.array.stock_type,
		 * R.layout.custom_spinner_text);
		 * adapter.setDropDownViewResource(R.layout.custom_spinner_dropdown);
		 */

		// List<Category> list = categoryDao.getAll();

		fromDate = (EditText) findViewById(R.id.buyin_from_date);
		toDate = (EditText) findViewById(R.id.buyin_to_date);
		simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
		simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		fromDate.setText(simpleDateFormat.format(fromCal.getTime()));
		toDate.setText(simpleDateFormat.format(toCal.getTime()));

		final CustomDatePicker fromPicker = new CustomDatePicker(this,
				fromDate, fromCal);
		fromDate.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				fromPicker.updateDate();
				fromPicker.show();
			}
		});

		final CustomDatePicker toPicker = new CustomDatePicker(this, toDate,
				toCal);
		toDate.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				toPicker.updateDate();
				toPicker.show();
			}
		});
		

		ImageView cancelBtn = (ImageView) findViewById(R.id.query_total);
		cancelBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if (categoryItems.size() < 1) {
					ViewUtil.makeToast(getApplicationContext(), "请选择打印内容");
					return;
				}
				print();
			}
		});

		/*
		 * ImageView cancelBtn = (ImageView)
		 * findViewById(R.id.buyin_query_close_btn);
		 * cancelBtn.setOnClickListener(new OnClickListener() { public void
		 * onClick(View v) { finish(); } });
		 */
	}

	public void search(View view) {
		Date btime;
		Date etime;
	//	_treeBuilder.clear();
		//_stateManager.clear();
		//goodsItems.clear();
		

		_stateManager = new InMemoryTreeStateManager<Statistics>();
		_treeBuilder = new TreeBuilder<Statistics>(_stateManager);
		_treeView.setAdapter(new GoodsQueryAdapter(this, _stateManager, 2));
		try {
			btime = simpleDateFormat.parse(fromDate.getText().toString());
			etime = simpleDateFormat2.parse(toDate.getText().toString()
					+ " 23:59:59");

			setPreferences("btime",fromDate.getText().toString());
			setPreferences("etime",toDate.getText().toString());
			categoryItems = (ArrayList) categoryDao.getAllParents();
			for (Category category : categoryItems) {
				float total = 0f;

				goodsItems = selloutDao.getAllSellOut(category.getId(),
						btime.getTime(), etime.getTime());

				for (Statistics statis : goodsItems) {
					total += Float.parseFloat(statis.getPrice());
				}
				
				Statistics statistics = new Statistics();
				statistics.setName(category.getCategory());
				statistics.setPrice(total + "元");
				//if(!_stateManager.isInTree(statistics))
				_treeBuilder.sequentiallyAddNextNode(statistics, 0);
				
				for (Statistics stat : goodsItems) {
					stat.setParent(category.getCategory());
					_treeBuilder.addRelation(statistics, stat);
				}
				map.put(statistics, goodsItems);
System.out.println("_treeBuilder=="+_treeBuilder.toString());
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}

	}

	

	private void print() {
		System.out.println("print/...........................");
		ViewUtil.showProgressDialog(GoodsQueryActivity.this, "正在处理...");
		new Thread() {
			public void run() {
				System.out.println("printing2222/...........................");
				// if (!shouldPrint.isChecked()) {
				if (mSerialPort != null) {
					mSendingThread = new SendingThread();
					mSendingThread.start();
				} else {
					System.out
							.println("serial is null/...........................");
				}
			}

		}.start();
		ViewUtil.cancelProgressDialog();

	}
	
	protected void onPrint(OutputStream mOutputStream) throws IOException {

		// TODO 按照格式补全打印信息

		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

		mOutputStream.write("\r\n".getBytes());
		mOutputStream.write(("      大兴农资安全监管系统\r\n").getBytes("gbk"));
		mOutputStream.write(("        " + name + "\r\n").getBytes("gbk"));
		mOutputStream.write(("           销售统计打印\r\n").getBytes("gbk"));
		mOutputStream.write(("统计起始日期:" + fromDate.getText().toString() + "\r\n").getBytes("gbk"));
		mOutputStream.write(("统计结束日期:" +toDate.getText().toString() + "\r\n").getBytes("gbk"));
		mOutputStream.write("================================\r\n"
				.getBytes("gbk"));
		mOutputStream.write("商品类别       价格合计\r\n".getBytes("gbk"));
		Iterator<Statistics> iterator = map.keySet().iterator();
		while (iterator.hasNext()) {
			Statistics key = iterator.next();
			System.out.println("map.get(key) is :" + map.get(key));
			
			
			mOutputStream.write((key.getName() + "         "+key.getPrice().substring(0,key.getPrice().length()-1)+"\r\n").getBytes("gbk"));
			
			ArrayList<Statistics> sells =  map.get(key);
			for (Statistics sellout :sells) {
				mOutputStream.write(("    "+sellout.getName() + "         "+sellout.getPrice().substring(0,sellout.getPrice().length())+"\r\n").getBytes("gbk"));

			}
		}

		mOutputStream.write(("===============================\r\n")
				.getBytes("gbk"));
		mOutputStream.write(("      打印日期:"
				+ simpleDateFormat.format(new Date()) + "   \r\n ")
				.getBytes("gbk"));
		mOutputStream.write("\r\n\r\n".getBytes());

	}
	
	private class SendingThread extends Thread {
		@Override
		public void run() {
			// while (!isInterrupted()) {
			try {
				if (mOutputStream != null) {
					onPrint(mOutputStream);
					return;
				} else {
					return;
				}
			} catch (IOException e) {
				e.printStackTrace();
				return;
			}
			// }
		}
	}

	@Override
	protected void onDataReceived(byte[] buffer, int size) {
		// TODO Auto-generated method stub
		
	}
	private void setPreferences(String key, String mPreferences) {
		// set preference
		SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
		SharedPreferences.Editor editor = settings.edit();
		editor.putString(key, mPreferences);
		editor.commit();
	}

}
